import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import whiteList from '@/utils/whiteList'

// 创建一个axios实例对象
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 基础地址
  timeout: 5000 // 超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 不在白名单中的请求将携带token
    if (!whiteList.some(item => config.url.includes(item))) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      Message({
        message: res.msg || '未知错误,请稍后重试',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || '未知错误,请稍后重试'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
